package com.cch.android.activity.view;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.cch.android.activity.ModelLandscapActivity;
import com.cch.android.activity.R;
import com.cch.android.util.Constant;


public class EdittActivity extends Activity implements OnClickListener{
	 /** 
     * 饱和度 
     */  
	private RelativeLayout edit_view_1;
    private LinearLayout edit_view_2,edit_view_3,edit_left,edit_right,edit_horizontalrotate,edit_verticalrotate;
    private Button mEditBtn_1,mEditBtn_2,mEditBtn_3,mEditBtn_shear,mEditBtn_shear_percent,mEditBtn_sharpen,setimage1_edit_colse,setimage1_save_btn;
    private ImageButton mEditBtn_leftRotate,mEditBtn_rightRotate,mEditBtn_HorRotate,mEditBtn_verRotate;
    private Context context;
    /**
	 * 图片view
	 */
	private ImageView mImageView;
	/**
	 * 初始化的图片
	 */
	private Bitmap mBitmap;
	/**
	 * 变化后的图片
	 */
	private Bitmap bmpSet;
	
	/**
	 * 图片剪辑比例参数
	 */
	public static  int IMAGE_SHEAR_WHITH = 1;
	
	public static  int IMAGE_SHEAR_HIGHT = 1;
	
	/**
	 * 图片剪辑参数
	 */
	public static final String IMAGE_UNSPECIFIED = "image/*";
	/**
	 * 图片剪辑结果参数
	 */
	public static final int PHOTORESOULT = 1;
	
	/**
	 * 本地图片路径集合
	 */
	private String path;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.model_setimage_edit);
		context = this;
        Intent intent = getIntent();
        mBitmap = intent.getParcelableExtra("imageBmp");
		initView();
		
	}
    private void initView(){
    	setimage1_edit_colse = (Button)findViewById(R.id.setimage1_edit_colse);
    	setimage1_save_btn = (Button)findViewById(R.id.setimage1_save_btn);
    	edit_view_1 = (RelativeLayout)findViewById(R.id.edit_view_1);
		edit_view_2 = (LinearLayout)findViewById(R.id.edit_view_2);
		edit_view_3 = (LinearLayout)findViewById(R.id.edit_view_3);
		edit_left = (LinearLayout)findViewById(R.id.edit_left);
		edit_right = (LinearLayout)findViewById(R.id.edit_right);
		edit_horizontalrotate = (LinearLayout)findViewById(R.id.edit_horizontalrotate);
		edit_verticalrotate= (LinearLayout)findViewById(R.id.edit_verticalrotate);
		mEditBtn_1 = (Button)findViewById(R.id.setimage1_edit_1);
		mEditBtn_2 = (Button)findViewById(R.id.setimage1_edit_2);
		mEditBtn_3 = (Button)findViewById(R.id.setimage1_edit_3);
		
		mEditBtn_shear = (Button)findViewById(R.id.edit_view_1_shear);
		mEditBtn_shear_percent  = (Button)findViewById(R.id.edit_view_1_shear_percent);
		mEditBtn_sharpen = (Button)findViewById(R.id.edit_view_3_sharpen);
		mEditBtn_leftRotate = (ImageButton)findViewById(R.id.edit_left_btn);
		mEditBtn_rightRotate = (ImageButton)findViewById(R.id.edit_right_btn);
		mEditBtn_HorRotate = (ImageButton)findViewById(R.id.edit_horizontalrotate_btn);
		mEditBtn_verRotate = (ImageButton)findViewById(R.id.edit_verticalrotate_btn);
		
		setimage1_edit_colse.setOnClickListener(this);
		setimage1_save_btn.setOnClickListener(this);
		mEditBtn_leftRotate.setOnClickListener(this);
		mEditBtn_rightRotate.setOnClickListener(this);
		mEditBtn_HorRotate.setOnClickListener(this);
		mEditBtn_verRotate.setOnClickListener(this);
		mEditBtn_shear.setOnClickListener(this);
		mEditBtn_shear_percent.setOnClickListener(this);
		mEditBtn_sharpen.setOnClickListener(this);
		mEditBtn_1.setOnClickListener(this);
		mEditBtn_2.setOnClickListener(this);
		mEditBtn_3.setOnClickListener(this);
		
		edit_left.setOnClickListener(this);
		edit_right.setOnClickListener(this);
		edit_horizontalrotate.setOnClickListener(this);
		edit_verticalrotate.setOnClickListener(this);
		edit_view_1.setVisibility(View.VISIBLE);
		 mImageView = ((ImageView) findViewById(R.id.setimage1_edit_image));
	        if(mBitmap!=null)
	        mImageView.setImageBitmap(mBitmap);
		
    }
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.setimage1_edit_1:
			mEditBtn_1.setBackgroundResource(R.drawable.btn_farmeweak_label_c);
			mEditBtn_2.setBackgroundResource(R.drawable.btn_farmeweak_label_a);
			mEditBtn_3.setBackgroundResource(R.drawable.btn_farmeweak_label_a);
			edit_view_1.setVisibility(View.VISIBLE);
			edit_view_2.setVisibility(View.GONE);
			edit_view_3.setVisibility(View.GONE);
			break;
		case R.id.setimage1_edit_2:
			mEditBtn_1.setBackgroundResource(R.drawable.btn_farmeweak_label_a);
			mEditBtn_2.setBackgroundResource(R.drawable.btn_farmeweak_label_c);
			mEditBtn_3.setBackgroundResource(R.drawable.btn_farmeweak_label_a);
			edit_view_1.setVisibility(View.GONE);
			edit_view_2.setVisibility(View.VISIBLE);
			edit_view_3.setVisibility(View.GONE);
			break;
		case R.id.setimage1_edit_3:
			mEditBtn_1.setBackgroundResource(R.drawable.btn_farmeweak_label_a);
			mEditBtn_2.setBackgroundResource(R.drawable.btn_farmeweak_label_a);
			mEditBtn_3.setBackgroundResource(R.drawable.btn_farmeweak_label_c);
			edit_view_1.setVisibility(View.GONE);
			edit_view_2.setVisibility(View.GONE);
			edit_view_3.setVisibility(View.VISIBLE);
			break;
		case R.id.edit_view_1_shear_percent:
				final String[] mItems = { "1:1", "2:3", "3:2" ,"3:4", "4:3", "16:9"};
				AlertDialog.Builder builder = new AlertDialog.Builder(context)
				        .setTitle(getString(R.string.select_edit_percen))
						.setItems(mItems,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										// 点击后弹出窗口选择了第几项
										switch (which) {
										case 0:
											IMAGE_SHEAR_WHITH = 1;
											IMAGE_SHEAR_HIGHT = 1;
											break;
										case 1:
											IMAGE_SHEAR_WHITH = 2;
											IMAGE_SHEAR_HIGHT = 3;
											break;
										case 2:
											IMAGE_SHEAR_WHITH = 3;
											IMAGE_SHEAR_HIGHT = 2;
											break;
										case 3:
											IMAGE_SHEAR_WHITH = 3;
											IMAGE_SHEAR_HIGHT = 4;
											break;
										case 4:
											IMAGE_SHEAR_WHITH = 4;
											IMAGE_SHEAR_HIGHT = 3;
											break;
										case 5:
											IMAGE_SHEAR_WHITH = 16;
											IMAGE_SHEAR_HIGHT = 9;
											break;
										}
										dialog.dismiss();
									}
								});
				builder.create().show();
			break;
		case R.id.edit_view_1_shear://剪切
			Drawable drawable = mImageView.getDrawable();
			if(drawable!=null)
				try {
					Constant.saveMyBitmap("setImage", 100, drawable);
				} catch (IOException e) {
					e.printStackTrace();
				}
			Uri uri = Uri.fromFile(new File(Constant.newPath + "setImage" + ".jpg"));
			startPhotoZoom(uri);
			break;
		case R.id.edit_view_3_sharpen://锐化
			Bitmap bmp = sharpenImageAmeliorate(getSetBitmap());
			if(bmp!=null)
			mImageView.setImageBitmap(bmp);
			break;
		case R.id.edit_left_btn:
		case R.id.edit_left:
			Bitmap bmpLeft = turnLeft(getSetBitmap());
			if(bmpLeft!=null)
			mImageView.setImageBitmap(bmpLeft);
			break;
		case R.id.edit_right_btn:
		case R.id.edit_right:
			Bitmap bmpRight=turnRight(getSetBitmap());
			if(bmpRight!=null)
				mImageView.setImageBitmap(bmpRight);
			break;
		case R.id.edit_horizontalrotate_btn:
		case R.id.edit_horizontalrotate:
			Bitmap bmphor=reverseBitmap(getSetBitmap(),0);
			if(bmphor!=null)
			mImageView.setImageBitmap(bmphor);
			break;
		case R.id.edit_verticalrotate_btn:
		case R.id.edit_verticalrotate:
			Bitmap bmpver = reverseBitmap(getSetBitmap(),1);
			if(bmpver!=null)
			mImageView.setImageBitmap(bmpver);
			break;
		case R.id.setimage1_edit_colse:
//			backToMain();
			finish();
			break;
		case R.id.setimage1_save_btn:
			saveToMain();
			break;
			}
			
		}  
	//图片裁剪方法  
	public void startPhotoZoom(Uri uri) {    
	    Intent intent = new Intent("com.android.camera.action.CROP");    
	    intent.setDataAndType(uri, IMAGE_UNSPECIFIED);    
	    intent.putExtra("crop", "true");    
	    // aspectX aspectY 是宽高的比例    
	    intent.putExtra("aspectX", IMAGE_SHEAR_WHITH);    
	    intent.putExtra("aspectY", IMAGE_SHEAR_HIGHT);    
	    // outputX outputY 是裁剪图片宽高    
	    intent.putExtra("outputX", 400);    //可以弄成设置裁剪
	    intent.putExtra("outputY", 400);    
	    intent.putExtra("return-data", true);    
	    startActivityForResult(intent, PHOTORESOULT);    
	}   
	 
    @Override
	protected void onDestroy() {
    	if (mBitmap != null) {
			mBitmap.recycle();
			System.gc();
			mBitmap=null;
		}
		if (bmpSet != null) {
			bmpSet.recycle();
			System.gc();
			bmpSet=null;
		}
		super.onDestroy();
	}
	@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 
        // TODO Auto-generated method stub 
        if(resultCode==RESULT_OK){ 
             // 处理结果    
             if (requestCode == PHOTORESOULT) {    
                 Bundle extras = intent.getExtras();    
                 if (extras != null) {    
                     Bitmap photo = extras.getParcelable("data");    
                     ByteArrayOutputStream stream = new ByteArrayOutputStream();    
                     photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)压缩文件    
                     mImageView.setImageBitmap(photo);
                     
                 }    
           
             }    
             super.onActivityResult(requestCode, resultCode, intent);    
        } 
         
    } 
    /** 
     * 图片锐化（拉普拉斯变换） 
     * @param bmp 
     * @return 
     */  
    private Bitmap sharpenImageAmeliorate(Bitmap bmp)  
    {  
        long start = System.currentTimeMillis();  
        // 拉普拉斯矩阵  
        int[] laplacian = new int[] { -1, -1, -1, -1, 9, -1, -1, -1, -1 };  
          
        int width = bmp.getWidth();  
        int height = bmp.getHeight();  
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
          
        int pixR = 0;  
        int pixG = 0;  
        int pixB = 0;  
          
        int pixColor = 0;  
          
        int newR = 0;  
        int newG = 0;  
        int newB = 0;  
          
        int idx = 0;  
        float alpha = 0.3F;  
        int[] pixels = new int[width * height];  
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);  
        for (int i = 1, length = height - 1; i < length; i++)  
        {  
            for (int k = 1, len = width - 1; k < len; k++)  
            {  
                idx = 0;  
                for (int m = -1; m <= 1; m++)  
                {  
                    for (int n = -1; n <= 1; n++)  
                    {  
                        pixColor = pixels[(i + n) * width + k + m];  
                        pixR = Color.red(pixColor);  
                        pixG = Color.green(pixColor);  
                        pixB = Color.blue(pixColor);  
                          
                        newR = newR + (int) (pixR * laplacian[idx] * alpha);  
                        newG = newG + (int) (pixG * laplacian[idx] * alpha);  
                        newB = newB + (int) (pixB * laplacian[idx] * alpha);  
                        idx++;  
                    }  
                }  
                  
                newR = Math.min(255, Math.max(0, newR));  
                newG = Math.min(255, Math.max(0, newG));  
                newB = Math.min(255, Math.max(0, newB));  
                  
                pixels[i * width + k] = Color.argb(255, newR, newG, newB);  
                newR = 0;  
                newG = 0;  
                newB = 0;  
            }  
        }  
          
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);  
        long end = System.currentTimeMillis();  
        Log.d("may", "used time="+(end - start));  
        return bitmap;  
    }  
    int rotate=0;
    //向右旋转
    public Bitmap turnRight(Bitmap bmp) {
            Matrix matrix = new Matrix();
            //setRotate和postRotate效果一样的
            rotate = rotate + 5;
//            matrix.setRotate(rotate);
            matrix.postRotate(90);
            //产生新的bitmap
            Bitmap resizebmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
            
           return resizebmp;
    }
    //向左旋转
    public Bitmap turnLeft(Bitmap bmp) {
            Matrix matrix = new Matrix();
             rotate = rotate - 5;
//            matrix.setRotate(rotate);
            matrix.postRotate(-90);
            Bitmap resizebmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
            
           return resizebmp;
           

           
    }
    /** 
     * 图片反转 
     *  
     * @param bm 
     * @param flag 
     *            0为水平反转，1为垂直反转 
     * @return 
     */  
    public static Bitmap reverseBitmap(Bitmap bmp, int flag) {  
        float[] floats = null;  
        switch (flag) {  
        case 0: // 水平反转  
            floats = new float[] { -1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f };  
            break;  
        case 1: // 垂直反转  
            floats = new float[] { 1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, 1f };  
            break;  
        }  
  
        if (floats != null) {  
            Matrix matrix = new Matrix();  
            matrix.setValues(floats);  
            return Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);  
        }  
  
        return null;  
    }  
   /* @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			backToLast();
			break;

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}*/
    private void backToMain(){
		Intent intent = new Intent();
		intent.putExtra("imageBmp", mBitmap);
		intent.setClass(this, ModelLandscapActivity.class);
		startActivity(intent);
	}
	/**
	 * 保存到sd卡 回到美化图片主界面
	 */
	private void saveToMain(){
		/*Drawable drawable = mImageView.getDrawable();
		if(drawable!=null)
			try {
				Constant.saveMyBitmap("setImage", 100, drawable);
			} catch (IOException e) {
				e.printStackTrace();
			}*/
		Intent intent = new Intent();
		intent.putExtra("imageBmp", getSetBitmap());
		intent.setClass(this, ModelLandscapActivity.class);
		startActivity(intent);
	}
	
	/**
	 * 得到处理的图片
	 * @return
	 */
	private Bitmap getSetBitmap(){
		if (mImageView != null) {
			if (bmpSet != null) {
				bmpSet.recycle();
				System.gc();
				bmpSet=null;
			}
			bmpSet = Constant.drawable2Bitmap(mImageView.getDrawable());
			return bmpSet;
		}
		return bmpSet;
	}
}
